package com.edu.marker.task;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import com.edu.marker.http.EHttpClient;
import com.edu.marker.http.EHttpUtils;
import com.edu.marker.http.ERequest;
import com.edu.marker.http.EResponse;
import com.edu.marker.http.ERequest.RequestType;
import com.edu.marker.task.WSAPI.WSACTION;
import com.edu.marker.utils.LogUtils;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;

public class WSTask extends AsyncTask<Void, Void, Object> {
	final LogUtils L = LogUtils.getLog(WSTask.class);
	private static String sCookie = "";
	private List<BasicNameValuePair> mParameter;
	private String mErrorCode;
	private int mAction;

	private TaskListener mTaskListener;
	private Context mContext;
	private Exception mReason;
	private Object mResult;

	public WSTask(Context context, TaskListener listener, 
			List<BasicNameValuePair> vp, int action) {
		mContext = context;
		mTaskListener = listener;
		mParameter = vp;
		mAction = action;
	}

	@Override
	public Object doInBackground(Void... arg0) {
		try {
			sCookie = getCookie((DefaultHttpClient)(EHttpClient.getInstance().getHttpClient()));
			EHttpClient.getInstance().execute(mSFRequest, mSFResponse, 
					mParameter, RequestType.API_POST);
			
		} catch (Exception e) {
			e.printStackTrace();
			mReason = e;
			return null;
		}

		return mResult;
	}

	@Override
	public void onPostExecute(Object result) {
		if (mContext == null) {
			clearTask();
			return;
		}

		if (mContext instanceof Activity && ((Activity) mContext).isFinishing()) {
			clearTask();
			return;
		}

		if (result == null || mReason != null) {
			mTaskListener.onFailed(mAction, mErrorCode, mReason);
		} else {
			mTaskListener.onSuccess(mAction, result);
		}
		clearTask();
	}
	
	private String getCookie(DefaultHttpClient httpClient) {
        List<Cookie> cookies = httpClient.getCookieStore().getCookies();
        StringBuilder sb = new StringBuilder();
        final int size = cookies.size();
        for (int i = 0; i < size; i++) {
            Cookie cookie = cookies.get(i);
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            if (!TextUtils.isEmpty(cookieName)
                     && !TextUtils.isEmpty(cookieValue)) {
                sb.append(cookieName + "=" );
                sb.append(cookieValue + ";" );
           }
       }
        
       System.out.println("=========>>>>>>>>>>>>>>.."+sb.toString());
       return sb.toString();
  }
	
	private final ERequest mSFRequest = new ERequest() {

		@Override
		public HttpUriRequest handleRequeste() throws IOException {
			final String serverUrl = mParameter.remove(0).getValue();
			final HttpPost post = new HttpPost(serverUrl);
			//post.setHeader("version", "");
			post.setHeader("Cookie", sCookie);
			return post;
		}
	};
	
	private final EResponse mSFResponse = new EResponse() {
		@Override
		public void handleReponse(Object obj) {
			InputStream in = (InputStream) obj;
			switch(mAction) {
			case WSACTION.ACT_QUSTIONPIC:
				mResult =WSParser.getDecodeBitmap(in);
				break;
			default:
				try {
					mResult = parse(in);
				} catch (Exception e) {
					mReason = e;
				}
			}
		}
	};
	
    private Object parse(InputStream in) throws JSONException, IOException {
    	if(in == null) {
    		throw new IllegalArgumentException("InputStreanm is null pointer...");
    	}
    	
    	final String jsonString = EHttpUtils.stream2String(in);
    	
    	switch(mAction) {
    	case WSACTION.ACT_LOGIN:
    		return WSParser.getUserInfo(jsonString);
    	case WSACTION.ACT_PAPER:
    		return WSParser.getPaperInfo(jsonString);
    	case WSACTION.ACT_QUSTIONTITLE:
    		return WSParser.getQuestionTitleInfo(jsonString);
    	case WSACTION.ACT_QUSTIONPICINFO:
    		return WSParser.getQuestionPicInfo(jsonString);
    	}
    	return null;
    }
    
	private void clearTask() {
		mTaskListener = null;
		mParameter = null;
		mContext = null;
	}

	public abstract interface TaskListener {
		public abstract void onSuccess(int action, Object result);

		public abstract void onFailed(int action, String errcode, Exception ex);
	}
}
